package com.telecom.sxint.app.api.controller.UccpMessageController;


import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.ObjectMapper;
import cn.zjtele.pubinfo.boot.redis.config.RedisHelper;
import cn.zjtele.pubinfo.common.http.response.ResponseData;
import com.alibaba.fastjson2.JSON;
import com.alibaba.nacos.common.http.param.MediaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.telecom.sxint.app.core.domain.entity.Messagepojo.App1UccpMessageParams;
import com.telecom.sxint.app.core.domain.entity.Query.PageData;
import com.telecom.sxint.app.core.domain.entity.Systempojo.App1YunwangWorkpojo.App1YunwangWorkOperationSummary;
import com.telecom.sxint.app.core.domain.entity.dto.MessageDTO;
import com.telecom.sxint.app.core.domain.entity.dto.UccpMessageParamsDTO;
import com.telecom.sxint.app.core.service.Messageservice.IApp1UccpMessageParamsService;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import okhttp3.internal.http.HttpHeaders;
import org.apache.http.HttpRequest;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p >
 *
 * @author
 * @since 2024-10-25
 */
@RestController
@RequestMapping("/app1-UccpMessage")
@Tag(name = "短信发送控制器", description = "信息导出管理")
@RequiredArgsConstructor
public class App1UccpMessageParamsController {

    @Autowired
    private IApp1UccpMessageParamsService app1UccpMessageParamsService;
    @Autowired
    private RedisHelper redisHelper;
    String cacheKey = "UccpMessageParams:list";
    /**
     * 新增
     * @param app1UccpMessageParams
     * @return
     */
    @Operation(summary = "新增", description = "新增")
    @PutMapping("/insertUccpMessageParams")
    public ResponseData insertUccpMessageParams(@RequestBody App1UccpMessageParams app1UccpMessageParams) {
        app1UccpMessageParamsService.save(app1UccpMessageParams);
        return ResponseData.success(app1UccpMessageParams);
    }

    /**
     * 查询全部
     * @return
     */
    @Operation(summary = "查询全部", description = "查询全部")
    @GetMapping("/queryAllUccpMessageParams")
    public ResponseData queryAllUccp() {
        List<App1UccpMessageParams> cacheData = (List<App1UccpMessageParams>) redisHelper.valueGet(cacheKey);
        if (cacheData != null && !cacheData.isEmpty()) {
            return ResponseData.success(cacheData);
        }

        return app1UccpMessageParamsService.queryAllUccp();
    }

    /**
     * 分页查询
     * @return
     */
    @Operation(summary = "分页查询", description = "分页查询")
    @PostMapping("/queryPageUccpMessageParams")
    public ResponseData<PageData<App1UccpMessageParams>> queryPageUccp(@RequestBody UccpMessageParamsDTO uccpMessageParamsDTO) {
        PageData<App1UccpMessageParams> pageData= app1UccpMessageParamsService.queryUccpPage(uccpMessageParamsDTO);
        return ResponseData.success(pageData);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Operation(summary = "根据id查询", description = "根据id查询")
    @GetMapping("/queryByIdUccpMessageParams")
    public ResponseData queryUccpById(@RequestParam Integer id) {
        return app1UccpMessageParamsService.queryUccpById(id);
    }

    /**
     * 修改
     * @param app1UccpMessageParams
     * @return
     */
    @Operation(summary = "修改", description = "修改")
    @PostMapping("/updateUccpMessageParams")
    public ResponseData updateUccpMessageParams(@RequestBody App1UccpMessageParams app1UccpMessageParams) {
        return app1UccpMessageParamsService.updateUccp(app1UccpMessageParams);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Operation(summary = "删除", description = "删除")
    @GetMapping("/deleteUccpMessageParams")
    public ResponseData deleteUccp(@RequestParam Integer id) {
        return app1UccpMessageParamsService.deleteUccp(id);
    }

    /**
     * 分页查询
     * @return
     */
    @Operation(summary = "分页查询升序", description = "分页查询")
    @PostMapping("/queryPageUccpMessageParamsAsc")
    public ResponseData<PageData<App1UccpMessageParams>> queryPageUccpAsc(@RequestBody UccpMessageParamsDTO uccpMessageParamsDTO) {
        PageData<App1UccpMessageParams> pageData= app1UccpMessageParamsService.queryUccpPageAsc(uccpMessageParamsDTO);
        return ResponseData.success(pageData);
    }

    /**
     * 分页查询
     * @return
     */
    @Operation(summary = "分页查询降序", description = "分页查询")
    @PostMapping("/queryPageUccpMessageParamsDesc")
    public ResponseData<PageData<App1UccpMessageParams>> queryPageUccpDesc(@RequestBody UccpMessageParamsDTO uccpMessageParamsDTO) {
        PageData<App1UccpMessageParams> pageData= app1UccpMessageParamsService.queryUccpPageDesc(uccpMessageParamsDTO);
        return ResponseData.success(pageData);
    }
    /**
     * 条件查询分页
     * @param condition
     * @return
     */
    @Operation(summary = "条件查询分页", description = "条件查询分页")
    @PostMapping("/UccpMessagequeryBySender")
    public ResponseData<PageData<App1UccpMessageParams>> queryBySender(@RequestBody UccpMessageParamsDTO uccpMessageParamsDTO, @RequestParam String condition) {
        PageData<App1UccpMessageParams> pageData= app1UccpMessageParamsService.queryAllMessagesPageByCondition(condition,uccpMessageParamsDTO);
        return ResponseData.success(pageData);
    }
    /**
     * 发送短信
     * @param
     * @return
     */
    @Operation(summary = "发送短信", description = "发送短信")
    @PostMapping("/sendUccpMessage")
    public ResponseData sendUccpMessage(@RequestBody MessageDTO messageDTO) throws UnsupportedEncodingException {
        String url = "http://134.108.13.13:8000/zjeop/rest/bssDomain/uccp/sendShortMessage";
        String responseString = "";
        String jsonBody = "{"
                + "\"accNbr\": \"" + messageDTO.getAccNbr() + "\","
                + "\"contentParam\": \"\","
                + "\"extOrderId\": \"\","
                + "\"orderContent\": \"" + messageDTO.getOrderContent() + "\","
                + "\"password\": \"141024\","
                + "\"requestTime\": \"" + messageDTO.getRequestTime() + "\","
                + "\"sceneId\": \"7812\","
                + "\"sendDate\": \"\","
                + "\"lanId\": \"571\","
                + "\"systemCode\": \"SXDXMP\","
                + "\"transactionId\": \"SXDXMP202205050921580000024809\","
                + "\"userAcct\": \"SXDXMP\","
                + "\"state\": \"\""
                + "}";
        JSONObject jsonObject = new JSONObject(jsonBody);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        httpPost.setHeader("X-APP-ID", "7932dcc94e4648823c0f364e4ec677e8");
        httpPost.setHeader("X-APP-KEY", "b079aa0cb63f47431d576abc2d489908");
        httpPost.setHeader("Content-Type", "application/json");

        // 设置请求体
        StringEntity stringEntity = new StringEntity(String.valueOf(jsonObject), "UTF-8");
        httpPost.setEntity(stringEntity);

        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            //将发送的信息插入数据库
            App1UccpMessageParams app1UccpMessageParams = JSON.parseObject(jsonBody, App1UccpMessageParams.class);
            //原有端口返回信息
            String responseData=EntityUtils.toString(response.getEntity());
            JSONObject msg=new JSONObject(responseData);
            responseString += msg.getStr("msg")+"\n";
            if(responseData.contains("成功!消息接收成功，放入队列：uccp_order")) {
                app1UccpMessageParams.setState("发送成功");
                app1UccpMessageParamsService.save(app1UccpMessageParams);
            }else {
                app1UccpMessageParams.setState("发送失败("+msg.getStr("msg")+")");
                app1UccpMessageParamsService.save(app1UccpMessageParams);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResponseData.success(responseString);
    }

    /**
     * 批量发送短信
     * @param
     * @return
     */
    @Operation(summary = "批量发送短信", description = "批量发送短信")
    @PostMapping("/sendMoreUccpMessage")
    public ResponseData sendMoreUccpMessage(@RequestBody List<MessageDTO> messageDTOS) throws UnsupportedEncodingException {
        String url = "http://134.108.13.13:8000/zjeop/rest/bssDomain/uccp/sendShortMessage";
        String responseString = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        // 设置请求头
        httpPost.setHeader("X-APP-ID", "7932dcc94e4648823c0f364e4ec677e8");
        httpPost.setHeader("X-APP-KEY", "b079aa0cb63f47431d576abc2d489908");
        httpPost.setHeader("Content-Type", "application/json");
        for(MessageDTO messageDTO : messageDTOS) {
            String jsonBody = "{"
                    + "\"accNbr\": \"" + messageDTO.getAccNbr()+ "\","
                    + "\"contentParam\": \"\","
                    + "\"extOrderId\": \"\","
                    + "\"orderContent\": \"" + messageDTO.getOrderContent() + "\","
                    + "\"password\": \"141024\","
                    + "\"requestTime\": \"" + messageDTO.getRequestTime() + "\","
                    + "\"sceneId\": \"7812\","
                    + "\"sendDate\": \"\","
                    + "\"lanId\": \"571\","
                    + "\"systemCode\": \"SXDXMP\","
                    + "\"transactionId\": \"SXDXMP202205050921580000024809\","
                    + "\"userAcct\": \"SXDXMP\","
                    + "\"state\": \"\""
                    + "}";
            JSONObject jsonObject = new JSONObject(jsonBody);
            // 设置请求体
            StringEntity stringEntity = new StringEntity(String.valueOf(jsonObject), "UTF-8");
            //设置编码
            httpPost.setEntity(stringEntity);
            try {
                CloseableHttpResponse response = httpClient.execute(httpPost);
                //将发送的信息插入数据库
                App1UccpMessageParams app1UccpMessageParams = JSON.parseObject(jsonBody, App1UccpMessageParams.class);
                //原有端口返回信息
                String responseData=EntityUtils.toString(response.getEntity());
                JSONObject msg=new JSONObject(responseData);
                responseString += msg.getStr("msg")+"\n";
                if(responseData.contains("成功!消息接收成功，放入队列：uccp_order")) {
                    app1UccpMessageParams.setState("发送成功");
                    app1UccpMessageParamsService.save(app1UccpMessageParams);
                }else {
                    app1UccpMessageParams.setState("发送失败("+msg.getStr("msg")+")");
                    app1UccpMessageParamsService.save(app1UccpMessageParams);
                }
                System.out.println("Response: " + responseData);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResponseData.success(responseString);
    }

}